/**
* File Name: client.c
* Auther: Jichang
* Environment: Fedora 7 server
* tcp socket Test
* client
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>

#define SERV_PORT 9527 // server port

// handle error
void sys_err(const char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	int cfd;
	int ret = 0, counter = 10;
	char buf[BUFSIZ];
	struct sockaddr_in serv_addr;  // init server address-struct.
	// init
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);
	inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr.s_addr);

	// create socket
	cfd = socket(AF_INET, SOCK_STREAM, 0);
	if(cfd == -1) {
		sys_err("socket error");
	}
	// connect(implicit binding).
	ret = connect(cfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
	if(ret != 0) {
		sys_err("connect error");
	}
	// write 6 times.
	while(--counter) {
		write(cfd, "hello\n", 6); 			// write to cfd(client).
		ret = read(cfd, buf, sizeof(buf)); 	// read from client.
		if(ret == -1) {
			sys_err("read error");
		}
		write(STDOUT_FILENO, buf, ret);
		sleep(1);
	}

	return 0;
}

